package com.logos.ruralrevitalization.repository;

import com.logos.ruralrevitalization.redis.RedisUtil;
import com.logos.ruralrevitalization.utils.TouristLoginUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import static com.logos.ruralrevitalization.constant.RedisConstant.RURAL_CHAT_HISTORY_KEY_PREFIX;
import static com.logos.ruralrevitalization.constant.RedisConstant.USER_CHAT_HISTORY_KEY_PREFIX;

@Component
public class RedisChatHistory implements ChatHistoryRepository{

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private TouristLoginUtil touristLoginUtil;

    @Override
    public void save(String userId, String chatId) {
        if(isUser()){
            redisUtil.addToSet(USER_CHAT_HISTORY_KEY_PREFIX + userId, chatId);
        }else{
            redisUtil.addToSet(RURAL_CHAT_HISTORY_KEY_PREFIX + userId, chatId);
        }
    }

    @Override
    public List<String> getChatIdList(String userId) {
        Set<String> chatIds = null;
        if (isUser()){
            chatIds = redisUtil.getAllFromSet(USER_CHAT_HISTORY_KEY_PREFIX + userId);
        }else{
            chatIds = redisUtil.getAllFromSet(RURAL_CHAT_HISTORY_KEY_PREFIX + userId);
        }
        if(chatIds == null || chatIds.isEmpty()) {
            return Collections.emptyList();
        }
        return chatIds.stream().sorted(String::compareTo).toList();
    }

    private Boolean isUser(){
        return touristLoginUtil.getType() == 1;
    }

}